package cn.com.eado.crm.vm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import cn.com.eado.crm.app.utils.LogUtil
import cn.com.eado.crm.m.bean.PostCompany
import cn.com.eado.crm.m.db.Company
import cn.com.eado.crm.m.db.Institute
import cn.com.eado.crm.m.repository.CompanyRepository
import cn.com.eado.crm.m.repository.InstituteRepository
import cn.com.eado.crm.model.AbsentLiveData
import cn.com.eado.crm.model.Resource

/**
 *
 */
class InstituteViewModel : ViewModel() {
    private val repository by lazy { InstituteRepository() }

    private val _load = MediatorLiveData<Boolean>()  //可观察的
    private val load: LiveData<Boolean> = _load
    //http请求参数
    var userId = 0
    var page = 1
    var rows = 20

    //指定请求返回的类型为:String（本app的所有请求基本使用此方式）
    val result: LiveData<Resource<Institute>> = Transformations.switchMap(load){ load ->
        if (load){
            LogUtil.e("tag", "load Company: userId = $userId, page=$page, rows=$rows")
            repository.loadInstitute(userId, page, rows)
        }else{
            AbsentLiveData.create()  //null
        }
    }

    fun setLoadCompany(b: Boolean){
        _load.value = b  //赋值时，会触发loginResult的执行。true:则执行repository.login(name, pwd, mac)
    }

    fun refresh(){
        page = 1
        _load.value?.let{ _load.value = it }
    }

    fun loadNextPage(){
        _load.value?.let{ _load.value = it }
    }


    ///////////////////////////////////////////////////////////////////////////////////////////
    var t: PostCompany? = null
    private val _post = MediatorLiveData<Boolean>()
    private val post: LiveData<Boolean> = _post

    val postCompany: LiveData<Resource<String>> = Transformations.switchMap(post){ post ->
        if (post){
            LogUtil.e("tag", "postCompany: userId = $userId, data=$t")
            repository.saveInstitute(userId, t!!)
        }else{
            AbsentLiveData.create()  //null
        }
    }

    fun setSave(b: Boolean){
        _post.value = b  //赋值时，会触发loginResult的执行。true:则执行repository.login(name, pwd, mac)
    }


    ///////////////////////////////////////////////////////////////////////////////////////////
    private val _search = MediatorLiveData<Boolean>()  //可观察的
    private val search: LiveData<Boolean> = _search
    var page2 = 1
    var instituteName = ""

    val searchInstitute: LiveData<Resource<Institute>> = Transformations.switchMap(search){ search ->
        if (search){
            LogUtil.e("tag", "postCompany: userId = $userId, data=$t")
            repository.searchInstitute(userId, rows, page2, instituteName)
        }else{
            AbsentLiveData.create()  //null
        }
    }

    fun setSearch(b: Boolean){
        _search.value = b  //赋值时，会触发loginResult的执行。true:则执行repository.login(name, pwd, mac)
    }

}